package pers.lxl.ajax.server.filter;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @version v1.0
 * @description: 跨域过渡器
 * @author: lxl
 * @date: 2018/9/9 14:39
 */
public class CrossFilter implements javax.servlet.Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        // 获得请求头中的Origin信息
        String origin = request.getHeader("Origin");
        if (origin != null) {
            // 带cookie的请求不能使用*通配符, 要使用确定的地址(可以从请求中动态获取,在返回)
            response.setHeader("Access-Control-Allow-Origin", origin);
        }

        // 获得请求头中的header(包括自定义的请求头)
        String headers = request.getHeader("Access-Control-Request-Headers");
        if (headers != null) {
            response.setHeader("Access-Control-Allow-Headers", headers);
        }

        response.setHeader("Access-Control-Allow-Methods", "*");
        response.setHeader("Access-Control-Max-Age", "3600");

        // 允许带cookie的跨域请求
        response.setHeader("Access-Control-Allow-Credentials", "true");

        filterChain.doFilter(request, response);
    }

    @Override
    public void destroy() {

    }
}
